/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.networking

import com.google.gson.Gson
import java.util.Map
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import java.util.Vector
import java.net.URLEncoder

class HttpClientUtils {
	static class Request{
		enum Type{
			POST,GET,PUT,DELETE
		}
		Type type
		String url;
		Object value;
		Class<?> returnType
	}
	def static call(Request req) {
		val jsonType = MediaType.parse("application/json;charset=UTF-8")
		var client = new OkHttpClient()
		var okhttp3.Request request = null
		switch (req.type) {
			case POST: {
				var body = RequestBody.create(new Gson().toJson(req.value), jsonType)
				request = new okhttp3.Request.Builder().url(req.url).post(body).build()
			}
			case PUT: {
				var body = RequestBody.create(new Gson().toJson(req.value), jsonType)
				request = new okhttp3.Request.Builder().url(req.url).put(body).build()
			}
			case DELETE: {
				var body = RequestBody.create(new Gson().toJson(req.value), jsonType)
				request = new okhttp3.Request.Builder().url(req.url).delete(body).build()
			}
			default: {
				var url = req.url;
				if(req.value instanceof Map){
					url = mapToUrlParam(req.url,req.value as Map<String,Object>);
				}
				request = new okhttp3.Request.Builder().url(req.url).build()
			}
		}
		var response = client.newCall(request).execute()
		if (response.isSuccessful) {
			System.out.println(response.code)
		}
		return new Gson().fromJson(response.body.string,req.returnType)
	}
	
	def static mapToUrlParam(String url, Map<String, Object> value) {
		var params = new Vector()
		for (kv : value.keySet) {
			var ps = URLEncoder.encode(String.valueOf(value.get(kv)), "UTF-8")
			params.add(#[kv, ps].join("="))
		}
		return #[url, params.join("&")].join("?");
	}
}


